module spi_testbench();

reg 		  clk;
reg 		  rst;
reg 		  cs;
reg 		  wr;
reg 		  rd;
reg		[1:0] read_addr;
reg		[1:0] write_addr;
reg		[7:0] data_out;
wire	[7:0] data_in;
wire		  irq_in;

wire		  sck_o;
wire		  mosi_i;
wire		  miso_o;

reg 		  cpol;
reg			  cpha;	
reg 		  csn;

wire	[7:0] tmpdata;

spi_top spi_master
(
  .clk_i(clk),         
  .rst_i(rst),
  .cs_i(cs),
  .wr_i(wr),
  .rd_i(rd),
  .read_addr_i(read_addr),
  .write_addr_i(write_addr), 
  .data_in(data_out),		
  .data_out(data_in),	 
  .irq_o(irq_in),
                
  .sck_o(sck_o),		
  .mosi_o(mosi_i),		
  .miso_i(miso_o)		
);

spi_slave spi_slave_reg
(
	.reset(rst),
	.sysclk(clk),
	.SPI_CLK(sck_o),
	.SPI_MISO(miso_o),
	.SPI_MOSI(mosi_i),
	.SPI_SS(csn)
);


//spi_slave_model spi_slave
//(
//	.csn(csn),
//	.sck(sck_o),
//	.di(mosi_i),
//	.do(miso_o),
//	
//	.cpol(cpol),
//	.cpha(cpha)
//
//);

always #5 clk = ~clk;

initial
begin
	clk = 0;
	rst = 0;
	cs = 0;
	wr = 0;
	rd = 0;
	read_addr = 2'd0;
	write_addr = 2'd0;
	data_out = 8'd0;
	cpol = 0;
	cpha = 0;
	csn = 1;
	
	#10;
	rst = 1;
	#10;
	rst = 0;

	write_register(2'd0,8'd10);
	write_register(2'd1,8'b10000011);//enable, cpha=0, cpol=0 4 byte per irq

	csn = 0;
	#1;
	write_register(2'd3,8'hC0);
	write_register(2'd3,8'hA1);
	write_register(2'd3,8'hA2);
	write_register(2'd3,8'hA3);
	write_register(2'd3,8'hA4);
	//write_register(2'd3,8'hA1);

	#100000;
	
	read_register(2'd3);
	read_register(2'd3);
	read_register(2'd3);
	read_register(2'd3);

	write_register(2'd3,8'h80);
	write_register(2'd3,8'hA1);
	write_register(2'd3,8'hA2);
	write_register(2'd3,8'hA3);
	write_register(2'd3,8'hA4);

	#500000;
	$stop;

	write_register(2'd1,8'd0);	//disable
	csn = 1;
	cpol = 0;
	cpha = 1;
	write_register(2'd1,8'b10100000);//enable, cpha = 1, cpol=0
	
	csn = 0;
	write_register(2'd3,8'd80);
	#1000;
	write_register(2'd1,8'd0);	//disable
	csn = 1;
	cpol = 1;
	cpha = 0;
	write_register(2'd1,8'b10010000);	//enable,cpha=0,cpol=1
	
	csn = 0;
	write_register(2'd3,8'd80);
	#1000;
	write_register(2'd1,8'd0);	//disable
	csn = 1;
	cpol = 1;
	cpha = 1;
	write_register(2'd1,8'b10110000);	//enable,cpha=1,cpol=1

	csn = 0;
	write_register(2'd3,8'd80);
	#1000;

	$stop;
end

task write_register;
	input [1:0] reg_addr;
	input [7:0] reg_data;

	begin 
	@(posedge clk);
	#1;
	cs = 1;
	write_addr = reg_addr;
	wr = 1;
	data_out = reg_data;
	@(posedge clk);
	#1;
	wr=0;
	write_addr = 8'b0;
	cs = 0;

	end
endtask

task read_register;
	input [1:0] reg_addr;

	begin
		@(posedge clk);
		#1;
		cs =1;
		read_addr = reg_addr;
		rd = 1;
		@(posedge clk);
		#1;
		rd =0;
		cs = 0;
		read_addr = 8'b0;
		#1;
	end
endtask	
	
endmodule







